import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:mybase/base/tool/globalMethod/FFSafeValue.dart';

import 'airplay_plus_platform_interface.dart';

/// An implementation of [AirplayPlusPlatform] that uses method channels.
class MethodChannelAirplayPlus extends AirplayPlusPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('airplay_plus');

  final eventChannel = const EventChannel('airplay_plus_eventChannel');

  /// 流
  final StreamController<bool> airPlayStatusStream = StreamController<bool>.broadcast();

  /// 初始化里开启监听
  MethodChannelAirplayPlus() {
    eventChannel.receiveBroadcastStream().listen((event) {
      String? type = globalSafeValueFromMap(event, "type");

      if (type == "connect") {
        num? status = globalSafeValueFromMap(event, "status");
        airPlayStatusStream.add(status == 1);
      }
    });
  }

  /**
   * @title 获取流
   */
  @override
  StreamController<bool> getAirPlayStatusStream() {
    return airPlayStatusStream;
  }

  Future<bool> getAirPlayStatus() async {
    num status = await methodChannel.invokeMethod('getAirPlayStatus') ?? 0;
    return status == 1;
  }

  Future<void> airPlay() async {
    return await methodChannel.invokeMethod('airPlay');
  }
}
